<template>
    <div class="chart-container">
        <Title :title="title" class="chart-title"></Title>
        <div ref="chartContainer" class="chart-content"></div>
    </div>
</template>
<script>
import { Rose } from '@antv/g2plot';
import { get } from '@/utils/request';

export default {
    data() {
        return {
            title: '风速监测',
            chart: null
        }
    },
    methods: {
        // 从接口获取风速数据
        async fetchWindSpeedData() {
            try {
                const response = await get('http://106.14.227.138:7001/dashboard/pageQueryTodayData?page=1&pageSize=10');
                
                if (response.status === 200 && response.data?.list?.length) {
                    return this.transformWindData(response.data.list);
                } else {
                    console.warn('未获取到风速数据');
                    return [];
                }
            } catch (error) {
                console.error('风速数据请求失败:', error);
                return [];
            }
        },

        // 转换数据为玫瑰图格式
        transformWindData(rawList) {
            const deviceDataMap = {};
            rawList.forEach(item => {
                const deviceId = `设备${item.device_id}`;
                if (!deviceDataMap[deviceId]) {
                    deviceDataMap[deviceId] = [];
                }
                deviceDataMap[deviceId].push({
                    windSpeed: parseFloat(item.wind_speed),
                    time: item.insert_time
                });
            });

            const result = [];
            Object.entries(deviceDataMap).forEach(([device, dataList]) => {
                dataList.sort((a, b) => a.time - b.time);
                
                // 内层数据（前一刻风速）
                if (dataList.length >= 1) {
                    result.push({
                        type: device,
                        value: dataList[0].windSpeed,
                        speedType: '前一刻风速',
                        isInner: true
                    });
                }
                // 外层数据（当前风速）
                if (dataList.length >= 2) {
                    result.push({
                        type: device,
                        value: dataList[1].windSpeed,
                        speedType: '当前风速',
                        isOuter: true
                    });
                }
            });

            return result;
        },

        // 初始化玫瑰图（调整文字大小和颜色）
        initRoseChart(data) {
            const container = this.$refs.chartContainer;
            if (!container || !data.length) return;

            if (this.chart) {
                this.chart.destroy();
            }

            this.chart = new Rose(container, {
                data: data,
                xField: 'type',
                yField: 'value',
                seriesField: 'speedType',
                isStack: true,
                radius: 0.9,
                angleField: 'type',
                sectorStyle: {
                    stroke: '#fff',
                    lineWidth: 1.5
                },
                // 调整花瓣文字样式
                label: {
                    visible: true,
                    formatter: (datum) => datum.type,
                    offset: -8,
                    style: {
                        fontSize: 8,  // 缩小字体
                        fill: '#ffffff',  // 白色文字
                        fontWeight: 'normal'
                    }
                },
                // 颜色说明图例
                legend: {
                    position: 'right',
                    layout: 'vertical',
                    itemName: { fontSize: 11 },
                    itemSpacing: 15
                },
                interactions: [
                    { type: 'element-active' },
                    { type: 'legend-active' }
                ],
                autoFit: true,
                height: '100%'
            });

            this.chart.render();
        }
    },
    async mounted() {
        const windData = await this.fetchWindSpeedData();
        this.$nextTick(() => this.initRoseChart(windData));
    },
    beforeDestroy() {
        if (this.chart) {
            this.chart.destroy();
        }
    }
}
</script>
<style scoped>
.chart-container {
    width: 100%;
    height: 220px;
    display: flex;
    flex-direction: column;
}

.chart-title {
    margin-bottom: 8px;
    padding-left: 10px;
}

.chart-content {
    flex: 1;
    width: 100%;
    padding-right: 70px;
    box-sizing: border-box;
}

::v-deep .g2-tooltip {
    background: #fff;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 8px 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

::v-deep .g2-tooltip-item {
    margin: 3px 0;
}

::v-deep .g2-legend {
    top: 50% !important;
    transform: translateY(-50%) !important;
}
</style>